package jp.sinya.clientsystem.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class JdbcUtils {

    //会自动去匹配src目录下的 c3p0-config.xml 文件来读取数据库连接池的配置
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    public static Connection getConnection() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection != null) {
            return connection;
        }
        return dataSource.getConnection();
    }

    public static DataSource getDataSource() {
        return dataSource;
    }

    public static void beginTransaction() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection != null) {
            throw new SQLException("已经开启事务连接，请不要重复开启");
        }
        connection = getConnection();
        connection.setAutoCommit(false);
        threadLocal.set(connection);
    }

    public static void commitTransaction() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection == null) {
            throw new SQLException("尚未开启事务连接，无法提交");
        }
        connection.commit();
        connection.close();
        threadLocal.remove();
    }

    public static void rollbackTransaction() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection == null) {
            throw new SQLException("尚未开启事务连接，无法回滚");
        }
        connection.rollback();
        connection.close();
        threadLocal.remove();
    }

    public static void releaseConnection(Connection temp) throws SQLException {
        Connection connection = threadLocal.get();
        if (connection == null) {
            temp.close();
        }
        if (connection != temp) {
            temp.close();
        }
    }
}
